package com.hy.study.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 解决Controller 之前的异常，例如404异常后台是捕获不到的
 *
 * @author huyong
 * @date 2024 年 01 月 05 日 17:51: 22
 */
@RestController
@Slf4j
public class FrontErrHandler implements ErrorController {
    @Override
    public String getErrorPath() {
        return "/error";
    }

    @GetMapping(value = "/error")
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Object error(HttpServletRequest request, HttpServletResponse response) {
        String pathInfo = request.getPathInfo();
        log.error("request  {} error response HttpCode:{}",pathInfo, response.getStatus());
        // 错误处理逻辑
        int status = response.getStatus();
        if (status == 404) {
            return new Result(StatusCode.REQUEST_NOT_FOUND, "访问地址不存在");
        } else if (status == 500) {
            return new Result(StatusCode.SYSTEM_ERR, "服务器运行异常");
        } else if (status >= 100 && status < 200) {
            return new Result(StatusCode.HTTP_ERROR_100, null);
        } else if (status >= 300 && status < 400) {
            return new Result(StatusCode.HTTP_ERROR_300, null);
        } else if (status >= 400 && status < 500) {
            return new Result(StatusCode.HTTP_ERROR_400, null);
        } else {
            return new Result(StatusCode.SYSTEM_ERR, "服务器运行异常");
        }

    }
}
